package ogs.game.protocol;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class MsgDecoder extends CumulativeProtocolDecoder {
	private static final String DECODER_STATE_KEY = MsgDecoder.class.getName() + ".STATE";
	public static final int HEADER_LENGTH = 8;
	public static final int MAX_PACK_SIZE = 1024 * 1024;

	private static class DecoderState {
        public boolean dirty = false;
        public int pCode = 0;
        public int len = 0;
        
        public void reset(){
        	dirty = false;
        	pCode = 0;
        	len = 0;
        }
    }
	
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		// 
		DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
        if (decoderState == null) {
            decoderState = new DecoderState();
            session.setAttribute(DECODER_STATE_KEY, decoderState);
        }
        
        if (!decoderState.dirty) {
            if (in.remaining() < HEADER_LENGTH) {
            	return false;
            }
            
            decoderState.pCode = in.getInt();
            decoderState.len = in.getInt();
            decoderState.dirty = true;
        } else if (in.prefixedDataAvailable(decoderState.len, MAX_PACK_SIZE))
    	{
    		byte[] bytes = new byte[decoderState.len];
    		in.get(bytes, 0, decoderState.len);

    		GameMsg msg = new GameMsg();
    		msg.protocolCode = decoderState.pCode;
    		msg.data = bytes;

    		decoderState.reset();
    		
    		out.write(msg);
    		return true;
    	}
        
		return false;
	}


}
